<template>
  <div class="book-management-container">
    <!-- 居中搜索区域 -->
    <div class="search-container">
      <n-input
        v-model:value="searchTitle"
        placeholder="搜索作品"
        clearable
        @keyup.enter="handleSearch"
        class="google-style-search"
      >
        <template #prefix>
          <SearchOutline />
        </template>
        <template #suffix>
          <n-tooltip placement="top" trigger="click">
            <template #trigger>
              <span class="filter-icon" @click="toggleFilter">
                <FilterOutline />
              </span>
            </template>
            <span>筛选</span>
          </n-tooltip>
        </template>
      </n-input>
      
      <!-- 筛选下拉面板 -->
      <div v-if="showFilter" class="filter-panel">
        <n-select
          v-model:value="selectedStatus"
          :options="statusOptions"
          placeholder="选择状态"
          clearable
          style="width: 200px;"
          @update:value="handleStatusChange"
        />
        <div class="filter-actions">
          <n-button text @click="resetSearch">重置</n-button>
        </div>
      </div>
    </div>

    <!-- 书籍卡片网格 -->
    <div class="books-grid-container">
      <div v-if="loading" class="loading-container">
        <n-spin size="large" />
      </div>
      <div v-else class="books-grid">
        <!-- 新建作品卡片 -->
        <n-card 
          class="create-book-card"
          hoverable
          @click="goToCreateBook"
        >
          <div class="create-book-content">
            <div class="create-icon">
              <AddOutline />
            </div>
          </div>
        </n-card>
        
        <!-- 现有作品卡片 -->
        <n-card
          v-for="book in books"
          :key="book.id"
          class="book-card"
          :class="`status-${book.status}`"
          hoverable
        >
          <div class="book-content">
            <div class="book-cover" @click="goToBookWorkspace(book)">
              <div class="cover-image-container">
                <n-image
                  v-if="book.coverImage"
                  :src="getCoverImageUrl(book)"
                  width="100%"
                  height="100%"
                  object-fit="contain"
                  preview-disabled
                />
                <div v-else class="no-cover">
                  <n-image
                    src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
                    width="100%"
                    height="100%"
                    object-fit="contain"
                    preview-disabled
                  />
                </div>
                <div class="cover-overlay">
                  <div class="overlay-content">
                    <n-button size="small" type="primary" ghost>
                      进入工作区
                    </n-button>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="book-info">
              <h3 class="book-title">{{ book.title }}</h3>
              
              <!-- 标签 -->
              <div class="book-tags" v-if="book.genre">
                <n-tag 
                  v-for="(tag, index) in getBookTags(book.genre)" 
                  :key="index"
                  size="small" 
                  type="info" 
                  round
                >
                  {{ tag }}
                </n-tag>
              </div>
              
              <!-- 元信息 -->
              <div class="book-meta">
                <div class="meta-left">
                  <span class="update-time">更新于 {{ formatUpdateTime(book.updateTime) }}</span>
                </div>
                <div class="meta-right">
                  <span class="create-time">{{ formatCreateTime(book.createTime) }}</span>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="book-actions">
                <n-button 
                  size="small" 
                  type="primary"
                  @click.stop="goToEditBook(book)"
                >
                  编辑
                </n-button>
                <n-button 
                  size="small" 
                  @click.stop="goToBookWorkspace(book)"
                >
                  创作
                </n-button>
                <n-button 
                  size="small" 
                  type="error"
                  @click.stop="handleDeleteBook(book)"
                >
                  删除
                </n-button>
              </div>
            </div>
          </div>
         </n-card>
       </div>
       
       <!-- 加载更多指示器 -->
       <div v-if="loadingMore" class="loading-more-container">
         <n-spin size="small" />
         <span class="loading-more-text">加载中...</span>
       </div>
     </div>
     
     <!-- 删除确认对话框 -->
     <n-modal v-model:show="showDeleteModal" preset="dialog" title="删除确认">
       <template #header>
         删除确认
       </template>
       确定要删除《{{ bookToDelete?.title }}》吗？此操作不可恢复。
       <template #action>
         <n-button size="small" @click="showDeleteModal = false">取消</n-button>
         <n-button size="small" type="error" @click="confirmDeleteBook">确认删除</n-button>
       </template>
     </n-modal>
   </div>
</template>

 <script setup lang="ts">
 import { ref, reactive, onMounted, nextTick, inject } from 'vue'

import {
  NCard,
  NButton,
  NInput,
  NSelect,
  NImage,
  NSpin,
  NTag,
  NModal,
  useMessage
} from 'naive-ui'
import {
  AddOutline,
  SearchOutline,
  FilterOutline
} from '@vicons/ionicons5'
import { bookService, type Book, type BookQueryParams } from '../services/book-service'
import BaseService from '../../shared/services/base-service'
import { useCurrentBookStore } from "../stores/current-book"

// 从TabManager获取标签页管理功能
const openTab = inject('openTab') as any

 // 响应式数据
const message = useMessage()
const currentBookStore = useCurrentBookStore()
 const loading = ref(false)
 const books = ref<Book[]>([])
 const searchTitle = ref('')
 const selectedStatus = ref<number | null>(null)
 const loadingMore = ref(false)
 const hasMore = ref(true)
 const showFilter = ref(false)
 const showDeleteModal = ref(false)
 const bookToDelete = ref<Book | null>(null)

// 切换筛选面板
const toggleFilter = () => {
  showFilter.value = !showFilter.value
}

// 格式化更新时间
const formatUpdateTime = (updateTime?: string) => {
  if (!updateTime) return '未更新'
  
  const now = new Date()
  const update = new Date(updateTime)
  const diff = now.getTime() - update.getTime()
  const hours = Math.floor(diff / (1000 * 60 * 60))
  
  if (hours < 1) {
    const minutes = Math.floor(diff / (1000 * 60))
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else {
    const days = Math.floor(hours / 24)
    return `${days}天前`
  }
}

// 格式化创建时间
const formatCreateTime = (createTime?: string) => {
  if (!createTime) return '未知时间'
  
  const date = new Date(createTime)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取书籍标签
const getBookTags = (genre?: string) => {
  if (!genre) return []
  return genre.split(',').map(tag => tag.trim()).filter(tag => tag)
}



// 处理删除书籍
const handleDeleteBook = (book: Book) => {
  bookToDelete.value = book
  showDeleteModal.value = true
}

// 确认删除书籍
const confirmDeleteBook = async () => {
  if (!bookToDelete.value || !bookToDelete.value.id) {
    message.error('无效的书籍信息')
    showDeleteModal.value = false
    return
  }
  
  try {
    const response = await bookService.deleteBook(bookToDelete.value.id)
    if (response.code === 0) {
      message.success('书籍删除成功')
      // 刷新书籍列表
      fetchBooks()
    } else {
      message.error(`删除失败: ${response.msg}`)
    }
  } catch (error) {
    console.error('删除书籍失败:', error)
    message.error('删除书籍失败，请稍后再试')
  } finally {
    showDeleteModal.value = false
    bookToDelete.value = null
  }
}

 // 分页配置
 const pagination = reactive({
   page: 1,
   pageSize: 12,
   itemCount: 0
 })

 // 状态选项
const statusOptions = [
  { label: '草稿', value: 0 },
  { label: '已发布', value: 1 },
  { label: '已下架', value: 2 }
]

 // 获取封面图片URL
const getCoverImageUrl = (book: Book) => {
  if (!book) return ''
  
  if (!book.coverImage) return ''
  
  // 如果是外部URL（http开头），直接返回
  if (book.coverImage.startsWith('http')) {
    return book.coverImage
  }
  
  // 如果是相对路径（/开头），构建完整的访问URL
  if (book.coverImage.startsWith('/')) {
    return `${BaseService.getApiUrl()}${book.coverImage}`
  }
  
  // 如果是uploads/开头的路径，直接添加API前缀
  if (book.coverImage.startsWith('uploads/')) {
    return `${BaseService.getApiUrl()}/${book.coverImage}`
  }
  
  // 其他情况，使用默认的图片访问路径
  if (!book.id) return ''
  return `${BaseService.getApiUrl()}/book/image/${book.id}/${book.coverImage.split('/').pop()}`
}

// 导航到创建书籍页面
 const goToCreateBook = () => {
   // 清除当前书籍，因为正在创建新书籍
   const currentBookStore = useCurrentBookStore()
   currentBookStore.clearCurrentState()
   
   // 使用标签页系统打开创建页面
   const tabId = 'create-book'
   const tabTitle = '新建书籍'
   const route = '/book/new'
   
   // 使用注入的openTab方法创建标签页
   openTab({
     id: tabId,
     title: tabTitle,
     route: route,
     closable: true
   })
 }

 // 导航到编辑书籍页面
 const goToEditBook = (book: Book) => {
   // 检查book.id是否存在
   if (!book || !book.id) {
     message.error('书籍信息无效，无法编辑')
     return
   }
   
   // 保存当前书籍到Pinia store
   const currentBookStore = useCurrentBookStore()
   currentBookStore.setCurrentBook(book)
   
   // 使用标签页系统打开编辑页面
   const tabId = `edit-book-${book.id}`
   const tabTitle = `编辑 - ${book.title}`
   const route = `/book/edit/${book.id}`
   
   // 使用注入的openTab方法创建标签页
   openTab({
     id: tabId,
     title: tabTitle,
     route: route,
     closable: true
   })
 }

 // 打开书籍标签页
const goToBookWorkspace = async (book: Book) => {
  try {
    // 检查book.id是否存在
    if (!book || !book.id) {
      message.error('书籍信息无效，无法打开')
      return
    }
    
    // 检查用户认证状态
    const { authPromptService } = await import('../../auth/services/auth-prompt-service')
    const isLoggedIn = await authPromptService.checkAndPromptLogin()
    if (!isLoggedIn) {
      return
    }

    // 判断当前侧边栏打开的是否是同一个书籍
    const isSameBook = currentBookStore.currentBook && currentBookStore.currentBook.id === book.id
    
    if (!isSameBook) {
      // 如果不是同一个书籍，设置当前书籍
      currentBookStore.setCurrentBook(book)
      
      // 保存当前书籍ID到本地存储
      localStorage.setItem('last_opened_book_id', book.id.toString())
    }
    
    // 使用NavigationSidebar的openOutlineTab方法打开最新大纲
    if (typeof window !== 'undefined' && (window as any).navigationSidebar) {
      try {
        await (window as any).navigationSidebar.openOutlineTab(book.id)
      } catch (error) {
        console.error('打开大纲失败:', error)
        message.error('打开大纲失败')
      }
    }
  } catch (error) {
    console.error('打开书籍工作区失败:', error)
    message.error('打开书籍工作区失败')
  }
}

 // 获取书籍列表
 const fetchBooks = async (isLoadMore = false) => {
   if (isLoadMore) {
     loadingMore.value = true
   } else {
     loading.value = true
   }
   
   try {
     const params: BookQueryParams = {
       page: pagination.page,
       size: pagination.pageSize,
       title: searchTitle.value || undefined,
       status: selectedStatus.value || undefined
     }
     
     const response = await bookService.getBooks(params)
     if (response.code === 0 && response.data) {
       if (isLoadMore) {
         books.value = [...books.value, ...response.data.records]
       } else {
         books.value = response.data.records
       }
       
       pagination.itemCount = response.data.total
       hasMore.value = books.value.length < response.data.total
     }
   } catch (error) {
     message.error('获取书籍列表失败')
     console.error('获取书籍列表失败:', error)
   } finally {
     loading.value = false
     loadingMore.value = false
   }
 }

 // 搜索
 const handleSearch = () => {
   pagination.page = 1
   fetchBooks()
 }

 // 重置搜索
 const resetSearch = () => {
   searchTitle.value = ''
   selectedStatus.value = null
   pagination.page = 1
   fetchBooks()
 }

 // 状态改变
 const handleStatusChange = () => {
   pagination.page = 1
   fetchBooks()
   showFilter.value = false // 状态改变后关闭筛选面板
}

 // 加载更多
 const loadMore = () => {
   if (loadingMore.value || !hasMore.value) return
   pagination.page += 1
   fetchBooks(true)
 }

 // 滚动事件处理
 const handleScroll = () => {
   const container = document.querySelector('.books-grid-container')
   if (!container) return
   
   const { scrollTop, scrollHeight, clientHeight } = container
   if (scrollTop + clientHeight >= scrollHeight - 100) {
     loadMore()
   }
 }

 // 初始化
 onMounted(() => {
   fetchBooks()
   nextTick(() => {
     const container = document.querySelector('.books-grid-container')
     if (container) {
       container.addEventListener('scroll', handleScroll)
     }
   })
 })
 </script>

<style scoped>
.book-management-container {
    padding: 0;
    background-color: #fafafa;
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

/* 居中搜索区域 */
.search-container {
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
  position: relative;
  padding: 20px;
}

/* 谷歌风格搜索框 */
.google-style-search {
  width: 100%;
  border-radius: 24px;
  border: 1px solid #dfe1e5;
  padding: 0 45px;
  transition: all 0.2s ease;
  background-color: white;
}

.google-style-search:hover {
  box-shadow: 0 1px 6px rgba(32, 33, 36, 0.28);
  border-color: rgba(223, 225, 229, 0);
}

.google-style-search:focus-within {
  box-shadow: 0 1px 6px rgba(32, 33, 36, 0.28);
  border-color: rgba(223, 225, 229, 0);
  outline: none;
}

.google-style-search .n-input__input-el {
  border: none !important;
  box-shadow: none !important;
  background-color: transparent;
  padding: 0;
  font-size: 16px;
  height: 46px;
}

.google-style-search .n-input__input-el:focus {
  box-shadow: none !important;
  border: none !important;
}

/* 筛选图标 */
.filter-icon {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  color: #5f6368;
  border-radius: 50%;
  transition: background-color 0.2s ease;
}

.filter-icon:hover {
  background-color: rgba(60, 64, 67, 0.08);
}

/* 筛选面板 */
.filter-panel {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 10px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  padding: 16px;
  /* 移除 z-index: 1000; */
  min-width: 300px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
}

/* 书籍网格容器 */
.books-grid-container {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

/* 书籍网格 */
.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  padding: 12px;
}

/* 新建作品卡片 */
.create-book-card {
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: visible;
  transition: all 0.3s ease;
  min-height: 180px;
  height: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  border: 2px dashed #e0e0e0;
}

.create-book-card:hover {
  border-color: #ff4757;
  background-color: #fff5f5;
  transform: translateY(-4px);
  box-shadow: 0 10px 20px rgba(255, 71, 87, 0.1);
}

.create-book-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.create-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff4757, #ff6348);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  box-shadow: 0 4px 12px rgba(255, 71, 87, 0.3);
}

/* 书籍卡片 */
.book-card {
  background-color: white;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: visible;
  transition: all 0.3s ease;
  min-height: 180px;
  height: auto;
  display: flex;
  flex-direction: column;
  position: relative;
}

.book-card:hover {
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-4px);
}

/* 书籍内容容器 */
.book-content {
  display: flex;
  height: 100%;
  width: 100%;
}

/* 书籍封面 */
.book-cover {
  width: 140px;
  height: 100%;
  background-color: #f8f8f8;
  position: relative;
  cursor: pointer;
  overflow: hidden;
  margin: 0;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.cover-image-container {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
}

.cover-image-container .n-image {
  width: 100% !important;
  height: 100% !important;
  object-fit: cover !important;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.book-cover:hover .cover-overlay {
  opacity: 1;
}

.overlay-content {
  transform: translateY(10px);
  transition: transform 0.3s ease;
}

.book-cover:hover .overlay-content {
  transform: translateY(0);
}

/* 书籍信息 */
.book-info {
  flex: 1;
  padding: 0 16px 0 16px;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: visible;
}

.book-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  min-height: 2.8em; /* 两行的最小高度 */
}

/* 书籍标签 */
.book-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  margin-bottom: auto;
  margin-top: 8px;
}

/* 书籍元信息 */
.book-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-top: auto;
  margin-bottom: 8px;
  font-size: 12px;
  color: #999;
  gap: 4px;
}

.meta-left {
  flex: 1;
}

.meta-right {
  flex-shrink: 0;
}

.create-time, .update-time {
  display: flex;
  align-items: center;
}

/* 书籍操作按钮 */
.book-actions {
  display: flex;
  gap: 8px;
  margin-top: auto;
  padding-bottom: 4px;
}

.book-actions .n-button {
  font-size: 12px;
  padding: 0 8px;
  height: 28px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  margin-bottom: 24px;
}

.empty-state {
   padding: 60px 0;
   text-align: center;
 }

 .loading-more-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px 0;
    gap: 8px;
  }

  .loading-more-text {
    font-size: 14px;
    color: #666;
  }
  
  .empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 60px 0;
    color: #999;
  }
@media (max-width: 768px) {
  .header-section {
    padding: 16px;
  }
  
  .page-title {
    font-size: 24px;
  }
  
  .search-container {
    padding: 0 16px 16px;
  }
  
  .google-style-search {
    height: 42px;
  }
  
  .google-style-search .n-input__input-el {
    height: 42px;
    font-size: 14px;
  }
  
  .filter-panel {
    left: 16px;
    right: 16px;
    transform: none;
    min-width: auto;
  }
  
  .books-grid {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 12px;
  }
  
  .book-card,
  .create-book-card {
    height: auto;
    min-height: 160px;
    overflow: visible;
  }
  
  .book-cover {
    width: 110px;
  }
  
  .book-info {
    padding: 12px;
  }
  
  .book-content {
    flex-direction: row;
  }
  
  .create-book-actions {
    width: 90%;
  }
}
</style>